
/**
 * 
 * $Id: IPAddresses.java,v 1.1 2006/03/01 03:53:04 liujiming Exp $ 
 * Created on 2005-12-28, 16:29:03
 */
package jm.lib.common;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

import jm.lib.util.StrUtil;



/**
 * Arrange a group of ip addresses and test whether an address in the group
 * 
 * @author JimingLiu
 * 
 */
public class IPAddresses {

	private Set normalAddresses;

	private List wildcardAddresses;

	public IPAddresses() {
		this.normalAddresses = new HashSet();
		this.wildcardAddresses = new ArrayList();
	}

	public IPAddresses(String addresses) {
		this();
		this.addAddresses(addresses);
	}

	/**
	 * add allowed addresses, seperated by ','
	 * You can use wildcard '*' and '?' in addresses 
	 * @param addresses
	 *            addresses seperated by ','
	 */
	public void addAddresses(String addresses) {
		String[] arr = StrUtil.split(addresses, ",", -1, true);
		addAddresses(arr);
	}

	/**
	 * add allowed addresses
	 * You can use wildcard '*' and '?' in addresses 
	 * @param addresses
	 */
	@SuppressWarnings("unchecked")
	public void addAddresses(String[] addresses) {
		if (null == addresses)
			return;
		int len = addresses.length;
		for (int i = 0; i < len; i++) {
			String address = addresses[i].trim();
			if (address.indexOf('*') == -1 && address.indexOf('?') == -1) {
				this.normalAddresses.add(address);
			} else {
				address = StrUtil.replace(address, "*", "\\d{1,3}");
				address = StrUtil.replace(address, ".", "\\.");
				address = StrUtil.replace(address, "?", "\\d");
				this.wildcardAddresses.add(Pattern.compile(address));
			}
		}
	}

	public boolean isAddressIn(String ip) {
		if (normalAddresses.contains(ip))
			return true;
		if (this.wildcardAddresses.size() > 0) {
			Iterator it = this.wildcardAddresses.iterator();
			while (it.hasNext()) {
				Pattern p = (Pattern) it.next();
				if (p.matcher(ip).matches())
					return true;
			}
		}
		return false;
	}

	
	public String toString() {
		StringBuffer buffer = new StringBuffer();
		buffer.append("[IPAddresses:");
		buffer.append(" normalAddresses: ");
		buffer.append(normalAddresses.toString());
		buffer.append(" wildcardAddresses: ");
		buffer.append(wildcardAddresses);
		buffer.append("]");
		return buffer.toString();
	}
	
	
}
